/*
 * miniFreeRTOS SOC System emulation.
 *
 * Copyright (c) 2024- yanl1229@163.com.
 * Written by yanl1229
 *
 * This code is licensed under the GPL.
 */

#include <stdlib.h>
#include "list.h"
#include "mm.h"

void list_init(list_head *list)
{
    struct list_node *p = kmalloc(sizeof(struct list_node));

    p->value = 0;
    p->next = NULL;
    p->priv = NULL;
    *list = p;
}

/**
 * entry插入到链表的尾部
 */
void list_add_tail(list_head list, struct list_node *entry)
{
    list_head tail = list;

    while (tail->next)
        tail = tail->next;

    tail->next = entry;
    entry->next = NULL;
}

/**
 * 将entry插入到list升序链表
 * value为键值,元素从小到大排列
 */
void list_add_order(list_head list, struct list_node *entry)
{

    list_head p = list;

    entry->next = NULL;

    while (p->next && p->next->value <= entry->value)
        p = p->next;

    entry->next = p->next;
    p->next = entry;
}

/**
 * 删除entry节点
 */
void list_remove(list_head list, struct list_node *entry)
{
    list_head p = list;

    if (p->next == NULL)
    	return ;

    while (p->next && p->next->priv != entry->priv)
        p = p->next;

    p->next = p->next->next;
    entry->next = NULL;
}

uint32_t get_value_of_first_entry(list_head list)
{
    return list->next->value;
}

/*
 * 链表是否为空
 */
int list_is_empty(list_head list)
{
    if (list->next)
        return 0;

    return 1;
}

/*
 * 链表节点数
 */
int list_count(list_head list)
{
    uint32_t count = 0;
    list_head p = list->next;

    while (p != NULL) {
        p = p->next;
        count++;
    }

    return count;
}

void *get_owner_of_first_entry(list_head list)
{
    return list->next->priv;
}
